﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;

namespace Mysoft.Rpa.ControlWeb.ApiClient
{
    public static class HttpHelper
    {

        public static T GetApi<T>(string apiName, string pragm = "")
        {
            string url = $"{Startup.ApiUrl}{apiName}";
            if (!string.IsNullOrEmpty(pragm))
            {
                url = $"{url}?{pragm}";
            }
            var client = new RestSharpClient(url);
            IRestRequest quest = new RestRequest();
            quest.Method = Method.GET;
            var request = client.Execute(quest);

            if (request.StatusCode != HttpStatusCode.OK)
            {
                return JsonConvert.DeserializeObject<T>(request.ErrorMessage);
            }
            
            T result = JsonConvert.DeserializeObject<T>(request.Content);

            return result;
        }

        public static TResult PostApi<TResult>(string apiName, object data)
        {
            var client = new RestClient($"{Startup.ApiUrl}{apiName}");
            IRestRequest quest = new RestRequest();
            quest.Method = Method.POST;
            quest.AddHeader("Accept", "application/json");
            quest.RequestFormat = DataFormat.Json;
            quest.AddJsonBody(data);
            var response = client.Execute(quest);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                return JsonConvert.DeserializeObject<TResult>(response.ErrorMessage);
            }
            
            TResult result = JsonConvert.DeserializeObject<TResult>(response.Content);
            return result;
        }
    }
}
